<template>
    <div class="koi-flex">
        <KoiCard>

            <el-descriptions title="文件信息" :column="2" border>

                <template #extra>
                    <el-tooltip content="刷新" placement="top">
                        <el-button circle icon="refresh" style="margin-left: 12px;" @click="handleRefresh()" />
                    </el-tooltip>

                    <el-tooltip content="修改" placement="top">
                        <el-button circle icon="Edit" @click="handleEdit()" />
                    </el-tooltip>
                </template>

                <!-- 是否保持原始文件名 -->
                <el-descriptions-item label="是否保持原始文件名">
                    {{ fileInfo.keepOriginFileName ? '是' : '否' }}
                </el-descriptions-item>

                <!-- 文件ID -->
                <el-descriptions-item label="文件ID">{{ fileInfo._id }}</el-descriptions-item>

                <!-- 支持的 MIME 类型 -->
                <el-descriptions-item label="支持的 MIME 类型">
                    <el-tag v-for="(type, index) in fileInfo.mimetype" :key="index" style="margin-right: 5px;">
                        {{ type }}
                    </el-tag>
                </el-descriptions-item>

                <!-- 文件大小 -->
                <el-descriptions-item label="文件大小">{{ formatFileSize(fileInfo.fileSize) }}</el-descriptions-item>

                <!-- 创建时间 -->
                <el-descriptions-item label="创建时间">{{ formatDate(fileInfo.createTime) }}</el-descriptions-item>

                <!-- 修改时间 -->
                <el-descriptions-item label="修改时间">{{ formatDate(fileInfo.modifyTime) }}</el-descriptions-item>

                <!-- 更新时间 -->
                <el-descriptions-item label="更新时间">{{ formatDate(fileInfo.updateTime) }}</el-descriptions-item>
            </el-descriptions>

            <KoiDialog ref="koiDialogRef" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancel"
                :loading="confirmLoading">
                <template #content>
                    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
                        <el-row>
                            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                                <el-form-item label="文件大小" prop="fileSize">
                                    <el-input v-model="form.fileSize" placeholder="请输入文件大小" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                                <el-form-item label="文件类型" prop="mimetype">
                                    <el-select v-model="form.mimetype" multiple filterable allow-create
                                        placeholder="请选择">
                                        <el-option v-for="item in form.mimetype" :key="item" :label="item"
                                            :value="item"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </template>
            </KoiDialog>

        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="filePage">
// 已使用字典案例
import { nextTick, ref, reactive, onMounted } from "vue";
// @ts-ignore
import { koiNoticeSuccess, koiNoticeError, koiMsgError } from "@/utils/koi.ts";
import { getFileConfig, updateFileConfig } from "@/api/system/file";

const fileInfo = ref<any>({})

const handleRefresh = async () => {

    try {
        fileInfo.value = {}

        const res: any = await getFileConfig()
        fileInfo.value = res
    } catch (error) {
        koiNoticeError('文件配置获取失败，请刷新重试🌻');
    }
}

// 格式化文件大小
const formatFileSize = (sizeInBytes: number) => {
    if (sizeInBytes < 1024) return `${sizeInBytes} KB`;
    let i = Math.floor(Math.log(sizeInBytes) / Math.log(1024));
    let size = (sizeInBytes / Math.pow(1024, i)).toFixed(2);
    return `${size} ${['KB', 'MB', 'GB', 'TB'][i]}`;
};

// 格式化日期
const formatDate = (dateString: string | number | Date) => {
    const date = new Date(dateString);
    return date.toLocaleString();
};

const title = ref('');
const formRef = ref<any>();
const koiDialogRef = ref();
const confirmLoading = ref(false);

const rules = reactive({
    // 验证规则
    fileSize: [
        { required: true, message: "请输入文件大小", trigger: "blur" },
    ],
    mimetype: [
        { required: true, message: "请选择文件类型", trigger: "blur" }
    ]
});

const form = ref({
    // 表单数据
    fileSize: "",
    mimetype: []
});

const handleEdit = () => {
    resetForm();
    title.value = "修改文件配置";
    handleEcho()
    koiDialogRef.value.koiOpen();
}

const handleEcho = () => {
    form.value.fileSize = fileInfo.value.fileSize
    form.value.mimetype = fileInfo.value.mimetype
}

const resetForm = () => {
    nextTick(() => {
        if (formRef.value) {
            formRef.value.resetFields();
        }
    });
    form.value = {
        fileSize: "",
        mimetype: []
    };
};

const handleConfirm = () => {
    if (!formRef.value) return;
    confirmLoading.value = true;
    formRef.value.validate(async (valid: any) => {
        if (valid) {

            try {
                await updateFileConfig(fileInfo.value._id, form.value)
                koiNoticeSuccess('文件配置修改成功🌻');
                confirmLoading.value = false;
                koiDialogRef.value.koiQuickClose();
                resetForm();
                handleRefresh();
            } catch (error) {
                confirmLoading.value = false;
                koiNoticeError('文件配置修改失败，请刷新重试🌻');
            }

        } else {
            koiMsgError('请检查表单信息是否填写正确🌻');
            confirmLoading.value = false;
        }
    })
}

const handleCancel = () => {
    koiDialogRef.value.koiClose();
}

onMounted(() => {
    // 获取数据表格数据
    handleRefresh();
});
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
    height: 400px;
}

.header {
    display: flex;
    flex-direction: column;
}

.title {
    color: #303133;
    font-size: 16px;
    margin-bottom: 16px;
    font-weight: bold;
}
</style>